import React, { useEffect, useState } from "react";
import {Card, Descriptions, message, Tag, Avatar, Space, Typography, Row, Col, Spin} from "antd";
import { useModel } from "@umijs/max";
import { getUserById } from "@/services/swagger/userController";
import {UserOutlined} from "@ant-design/icons";

const { Title, Text } = Typography;

const My: React.FC = () => {
  const [userVo, setUserVo] = useState<API.UserVo>({});
  const [loading, setLoading] = useState<boolean>(true);
  const state = useModel('@@initialState');
  const currentUser = state.initialState?.currentUser;

  useEffect(() => {
    const fetchUser = async () => {
      if (!currentUser?.id) {
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        const res = await getUserById({ userId: currentUser.id });

        if (res.code === 0) {
          setUserVo(res.data || {});
          message.success("获取用户信息成功");
        } else {
          message.error(`获取用户信息失败: ${res.message || '未知错误'}`);
        }
      } catch (error) {
        console.error("获取用户信息出错:", error);
        message.error("网络异常，请稍后重试");
      } finally {
        setLoading(false);
      }
    };

    fetchUser();
  }, [currentUser]);

  // 处理用户角色显示
  const renderUserRoleTag = () => {
    const role = userVo.userRole;
    let color = "blue";
    let text = "普通用户";

    if (role === "admin") {
      color = "green";
      text = "管理员";
    } else if (role === "super_admin") {
      color = "red";
      text = "超级管理员";
    }

    return <Tag color={color} style={{ fontSize: '14px' }}>{text}</Tag>;
  };

  // 处理用户简介的显示
  const renderUserProfile = () => {
    if (!userVo.userProfile) {
      return <Text type="secondary">暂无简介</Text>;
    }
    return <Text>{userVo.userProfile}</Text>;
  };

  return (
    <div style={{ padding: '24px', maxWidth: 1200, margin: '0 auto' }}>
      <Title level={2} style={{ marginBottom: 32, textAlign: 'center' }}>
        个人中心
      </Title>

      {loading ? (
        <div style={{ textAlign: 'center', padding: '60px 0' }}>
          <Space size="middle">
            <Avatar size={120} icon={<UserOutlined />} style={{ backgroundColor: '#1890ff' }} />
            <Spin size="large" />
          </Space>
        </div>
      ) : (
        <Row gutter={[38, 38]} style={{ maxWidth: '1600px', margin: '0 auto', width: '100%' }}>
          <Col xs={24} md={10} lg={8} xl={7}>
            <Card
              title={<Title level={4} style={{ textAlign: 'center' }}>个人资料</Title>}
              bordered={false}
              style={{ height: '100%' }}
            >
              <div style={{ textAlign: 'center', marginBottom: 38 }}>
                <Avatar
                  size={100}
                  src={userVo.userAvatar || undefined}
                  icon={<UserOutlined />}
                  style={{
                    backgroundColor: '#1890ff',
                    marginBottom: 16,
                    fontSize: '32px'
                  }}
                />
                <Title level={4} style={{ marginBottom: 8 }}>
                  {userVo.userName || '未设置'}
                </Title>
                <Text type="secondary" style={{ fontSize: '14px' }}>
                  @{userVo.userAccount || '未设置'}
                </Text>
              </div>

              <Descriptions
                column={1}
                bordered
                size="middle"
                labelStyle={{ fontWeight: 500, width: '45%' }}
              >
                <Descriptions.Item label="用户ID">
                  <Text code style={{ fontSize: '12px' }}>{userVo.id || 'N/A'}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="用户角色">
                  {renderUserRoleTag()}
                </Descriptions.Item>
                <Descriptions.Item label="注册时间">
                  {userVo.createTime
                    ? new Date(userVo.createTime).toLocaleDateString('zh-CN', {
                      year: 'numeric',
                      month: '2-digit',
                      day: '2-digit'
                    })
                    : 'N/A'}
                </Descriptions.Item>
              </Descriptions>
            </Card>
          </Col>

          {/* 右侧：详细信息 */}
          <Col xs={24} md={15} lg={16} xl={17}>
            <Card
              title={<Title level={4} style={{ textAlign: 'center' }}>详细信息</Title>}
              bordered={false}
              style={{ height: '100%' }}
            >
              <Descriptions
                column={1}
                bordered
                size="middle"
                labelStyle={{ fontWeight: 500, width: '30%' }}
              >
                <Descriptions.Item label="用户账号">
                  <Text copyable style={{ fontSize: '14px' }}>{userVo.userAccount || '未设置'}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="用户昵称">
                  <Text style={{ fontSize: '14px' }}>{userVo.userName || '未设置'}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="用户简介">
                  {renderUserProfile()}
                </Descriptions.Item>
              </Descriptions>
            </Card>
          </Col>
        </Row>
      )}
    </div>
  );
};

export default My;
